<template>
  <div class="mb-10">
    <p class="text-lg font-bold">{{ props.attributeItem.attr_name }}</p>
    <a-checkbox-group
      v-model:value="state.checkedList"
      :options="props.attributeItem.attr_vals"
      @change="handleChange"
    />
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, toRaw, watch } from 'vue';

  interface stateModel {
    checkedList: string[];
  }

  const props = defineProps({
    attributeItem: {
      type: Object,
      required: true,
      default() {
        return {};
      },
    },
  });

  const emits = defineEmits(['getCheckbox']);

  const state: stateModel = reactive({
    checkedList: [],
  });

  const handleChange = () => {
    const attr = {
      attr_id: props.attributeItem.attr_id,
      attr_value: toRaw(state.checkedList).join(','),
    };
    emits('getCheckbox', attr);
  };

  onMounted(() => {
    state.checkedList = [...props.attributeItem.attr_vals];
  });
  watch(
    () => props.attributeItem.attr_value,
    () => {
      if (props.attributeItem.attr_value) {
        state.checkedList = [...props.attributeItem.attr_value];
      }
    },
  );
</script>
